package com.hoshiicloud.goods.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.query.OmnipotentParam;
import com.hoshiicloud.common.query.OmnipotentWrapper;
import com.hoshiicloud.common.update.UpdateBatchParam;
import com.hoshiicloud.goods.component.GoodsProFileComponent;
import com.hoshiicloud.goods.entity.sku.BaseSku;
import com.hoshiicloud.goods.entity.sku.ExtSku;
import com.hoshiicloud.goods.feign.IdGeneratorService;
import com.hoshiicloud.goods.mapper.sku.BaseSkuMapper;
import com.hoshiicloud.goods.param.ListSkuSpuParam;
import com.hoshiicloud.goods.param.sku.SkuBaseListParam;
import com.hoshiicloud.goods.service.BaseSkuService;
import com.hoshiicloud.goods.service.ExtSkuService;
import com.hoshiicloud.goods.vo.ListSpuSkuVo;
import com.hoshiicloud.goods.vo.sku.BaseSkuVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

;

/**
 * <p>
 * 基础商品表SKU 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-04
 */
@Slf4j
@Service
public class BaseSkuServiceImpl extends ServiceImpl<BaseSkuMapper, BaseSku> implements BaseSkuService {

    @Autowired
    private IdGeneratorService idGeneratorService;
    /**
     * @param id
     * @return BaseSku
     * @description: 根据id查询基础商品表SKU
     */
    @Override
    @Cacheable(cacheNames = "BaseSku", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "商品管理-基础商品表SKU-查询基础商品表SKU ")
    public BaseSku getById(Long id) {
        return baseMapper.selectById(id);
    }


    /**
     * @param entity
     * @return boolean
     * @description: 新增基础商品表SKU
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "BaseSku", allEntries = true)
    @Logable(authName = "商品管理-基础商品表SKU-新增基础商品表SKU")
    public boolean save(BaseSku entity) {

        // 生成主键id
        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }

        // 保存数据库
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());

        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return true;
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改基础商品表SKU
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "BaseSku", allEntries = true)
    @Logable(authName = "商品管理-基础商品表SKU管理-修改基础商品表SKU")
    public boolean updateById(BaseSku entity) {

        // 更新数据
        entity.setUpdatedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }

    /**
     * @param page         分页
     * @param queryWrapper 查询条件
     * @param key          缓存key
     * @return 分页查询基础商品表SKU
     */
    @Override
    @Logable(authName = "商品管理-基础商品表SKU管理-分页查询基础商品表SKU")
    @Cacheable(cacheNames = "BaseSku", key = "T(com.hoshiicloud.common.utils.DigestUtils).md5(#root.targetClass.simpleName+':'+#root.methodName+':'+#key)")
    public IPage getPage(IPage page, Wrapper queryWrapper, String key) {
        return baseMapper.selectPage(page, queryWrapper);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "BaseSku", allEntries = true)
    @Logable(authName = "商品管理-基础商品表SKU管理-删除基础商品表SKU")
    public boolean deleteById(Long id) {

        // 根据id查询商品是否存在
        BaseSku entity = this.getById(id);
        if (entity == null) {
            throw new ServiceException("删除基础商品表SKU异常，无法找到基础商品表SKU记录");
        }

        // 删除商品
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        }
        return true;
    }

    @Override
    @Cacheable(cacheNames = "BaseSku", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "商品管理-基础商品表SKU管理-根据id集合查询基础商品表SKU")
    public List<BaseSku> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }

    /**
     * 多条件批量查询
     */
    @Override
    public List<BaseSku> listBaseSku(BaseSku baseSku) {
        try {
            QueryWrapper<BaseSku> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(baseSku.getSpuId() != null, BaseSku::getSpuId, baseSku.getSpuId())
                    .eq(StringUtils.isNotBlank(baseSku.getSkuNo()), BaseSku::getSkuNo, baseSku.getSkuNo())
                    .eq(StringUtils.isNotBlank(baseSku.getBarCode()), BaseSku::getBarCode, baseSku.getBarCode())
                    .eq(StringUtils.isNotBlank(baseSku.getPacketCode()), BaseSku::getPacketCode, baseSku.getPacketCode())
                    .eq(baseSku.getIsStored() != null, BaseSku::getIsStored, baseSku.getIsStored())
                    .eq(StringUtils.isNotBlank(baseSku.getExtendProperty()), BaseSku::getExtendProperty, baseSku.getExtendProperty())
                    .eq(StringUtils.isNotBlank(baseSku.getExtendSpec()), BaseSku::getExtendSpec, baseSku.getExtendSpec())
                    .eq(StringUtils.isNotBlank(baseSku.getSkuTitle()), BaseSku::getSkuTitle, baseSku.getSkuTitle())
                    .eq(baseSku.getStatus() != null, BaseSku::getStatus, baseSku.getStatus())
                    .eq(StringUtils.isNotBlank(baseSku.getSalesUnit()), BaseSku::getSalesUnit, baseSku.getSalesUnit())
                    .eq(baseSku.getWeight() != null, BaseSku::getWeight, baseSku.getWeight())
                    .eq(baseSku.getStrategy() != null, BaseSku::getStrategy, baseSku.getStrategy())
                    .eq(baseSku.getVendorSelf() != null, BaseSku::getVendorSelf, baseSku.getVendorSelf())
                    .eq(baseSku.getVendorId() != null, BaseSku::getVendorId, baseSku.getVendorId())
                    .eq(baseSku.getStockEnough() != null, BaseSku::getStockEnough, baseSku.getStockEnough())
                    .eq(baseSku.getDeleted() != null, BaseSku::getDeleted, baseSku.getDeleted());
            return baseMapper.selectList(queryWrapper);
        }catch (Exception e) {
            log.info("批量查询BaseSku信息失败");
            throw new ServiceException("批量查询BaseSku信息失败");
        }
    }


    /**
     * 批量下架baseSku
     */
    @CacheEvict(cacheNames = "BaseSku", allEntries = true)
    @Transactional
    @Override
    public Boolean baseSkuShelvesDown(List<BaseSku> baseSkus, Integer status) {

        // 查询需要下架的 BaseSku(一个BaseSpu 对应 一个至多个BaseSku)
        if (baseSkus.isEmpty()) {
            throw new ServiceException("下架失败， 没有找到相关BaseSku记录");
        }

        // 设置下架信息
        baseSkus.stream().forEach(baseSku -> {
            baseSku.setStatus(status);
            baseSku.setUpdatedTime(LocalDateTime.now());
        });

        // 批量下架
        boolean isDowm = this.updateBatchById(baseSkus);
        if (!isDowm) {
            throw new ServiceException(CommonError.error("下架baseSku失败"));
        }
        return true;
    }



    @CacheEvict(cacheNames = "BaseSku", allEntries = true)
    @Logable(authName = "添加BaseSku返回BaseSku")
    @Override
    public BaseSku saveBaseSku(BaseSku entity) {
        // 生成主键id
        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }

        // 保存数据库
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());

        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return entity;
    }


    @CacheEvict(cacheNames = "BaseSku", allEntries = true)
    @Logable(authName = "根据自定义条件批量更新")
    @Override
    public boolean updateBatchByWrapper(UpdateBatchParam<BaseSku> updateBatchParam) {
        BaseSku updateEntity = updateBatchParam.getUpdateEntity();
        QueryWrapper<BaseSku> wrapper = updateBatchParam.getWrapper();
        return this.update(updateEntity, wrapper);
    }

    @Override
    @Logable(authName = "根据自定义条件获取BaseSku集合")
    @Cacheable(cacheNames = "BaseSku", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public List<BaseSkuVo> listByParam(SkuBaseListParam param, String key) {
        QueryWrapper<BaseSku> qbase = new QueryWrapper<>();
        qbase.lambda().eq((null != param.getStoreId()&& 0!=param.getStoreId()),BaseSku::getStoreId,param.getStoreId())
                .eq((null != param.getDeleted()&& 0!=param.getDeleted()),BaseSku::getDeleted, param.getDeleted())
                .eq((null != param.getDistributorStatu()),BaseSku::getDistributorStatu,param.getDistributorStatu())
                .eq((null != param.getSpuId() && 0!=param.getSpuId()), BaseSku::getSpuId, param.getSpuId());

        List<BaseSku> list1 = baseMapper.selectList(qbase);
        List<BaseSkuVo> rs = JSONObject.parseArray(JSONObject.toJSONString(list1),BaseSkuVo.class);
        if(param.getChangeOther() == 1){
            for(BaseSkuVo v:rs){

            }
        }
        return rs;
    }

    /**
     * 批量更新
     */
    @Override
    public boolean updateBatch(OmnipotentParam<BaseSku> param) {
        OmnipotentWrapper<ExtSku> omiWrapper = new OmnipotentWrapper<>();
        UpdateWrapper updateWrapper = omiWrapper.getUpdateWrapper(param.getWrappers());
        BaseSku entityUpdate = param.getEntity();
        return this.update(entityUpdate, updateWrapper);
    }

    /**
     * 批量查询
     */
    @Override
    public List<BaseSku> queryBatch(List<OmnipotentWrapper> params) {
        OmnipotentWrapper<BaseSku> wrappers = new OmnipotentWrapper<>();
        QueryWrapper<BaseSku> wrapper = wrappers.getWrapper(params);
        return baseMapper.selectList(wrapper);
    }
}
